import { defineStore } from 'pinia'
import { request as axios } from '../utils/axios.js'
import bus from '../utils/bus.js'
import { throttle } from 'lodash';
import tiaoJianTxt from '@/utils/tiaojiandan.js'
const { ipcRenderer } = require('electron');




export const mainStore = defineStore('main', {//storeMain
    state: () => ({
        heyueinfo: [],
        selectHeyue: undefined,
        classHeyue: { '外盘': {}, '期货': {} },
        classHeyueIndex: localStorage.getItem('classHeyueIndex') || '期货',
        zixuanHeyue: localStorage.getItem('zixuanHeyue') ? JSON.parse(localStorage.getItem('zixuanHeyue')) : {},
        ConfigJsInfo: undefined,
        xianlu: undefined,
        username: 'serverclient',
        password: 'serverpass',
        rightViewXY: null,
        fffTime: null
    }),
    actions: {
        async getHeyueinfo(url, parameter) {
            if (this.fffTime) {
                clearTimeout(this.fffTime)
                this.fffTime = null
                return
            }
            try {
                let res = await axios.post(this.xianlu.url + '/' + url, parameter)
                if (res.code == 0) {
                    this.heyueinfo = res.data
                    // this.selectHeyue = res.data[0]
                    this.heyueinfo.forEach(item => {
                        if (this.classHeyue[item.shichang_name]) {
                            this.classHeyue[item.shichang_name][item.heyue_bh] = item
                            if (!this.selectHeyue && this.classHeyueIndex == item.shichang_name) {
                                this.selectHeyue = item
                            }
                        } else {
                            this.classHeyue[item.shichang_name] = {}
                            this.classHeyue[item.shichang_name][item.heyue_bh] = item
                            if (!this.selectHeyue && this.classHeyueIndex == item.shichang_name) {
                                this.selectHeyue = item
                            }
                        }
                        if (item.jiekou_id == 1) {
                            this.classHeyue['期货'][item.heyue_bh] = item
                            if (!this.selectHeyue && this.classHeyueIndex == '期货') {
                                this.selectHeyue = item
                            }
                        }
                        if (item.jiekou_id == 2) {
                            this.classHeyue['外盘'][item.heyue_bh] = item
                            if (!this.selectHeyue && this.classHeyueIndex == '外盘') {
                                this.selectHeyue = item
                            }
                        }
                    })
                }
            } catch (error) {
                this.fffTime = setTimeout(() => {
                    clearTimeout(this.fffTime)
                    alert('网络错误请检查网络后F5刷新重试！')
                }, 1000)
            }
            // return this.getConfigJsInfo()
        },
        async getConfigJsInfo(url, parameter) {
            if (this.fffTime) {
                clearTimeout(this.fffTime)
                this.fffTime = null
                return
            }
            try {
                let res = await axios.get('http://146.56.245.135:8098/khd/config.json?fff=' + new Date() / 1)
                // let res = await axios.get('https://ceshi1.zchczz.com/khd/config.json?fff=' + new Date() / 1)
                // let res = await axios.get('https://conf.tianhengqihuo.com/khd/config.json?fff=3')
                let wsType = 'ws://',
                    httpType = 'http://'
                if (res.is_ssl == 1) {
                    wsType = 'wss://'
                    httpType = 'https://'
                }
                res.uploadUrl = httpType + res.uploadUrl
                res.updateplay = httpType + res.updateplay
                res.ipUrl = httpType + res.ipUrl
                res.mqttUrl.wsMqtt_hz = wsType + res.mqttUrl.wsMqtt_hz
                res.mqttUrl.wsMqtt_bj = wsType + res.mqttUrl.wsMqtt_bj
                res.mqttUrl.wsMqtt_qd = wsType + res.mqttUrl.wsMqtt_qd
                res.tradeLine = res.tradeLine.map(item => {
                    item.node = wsType + item.node
                    item.url = httpType + item.url
                    item.mnurl = httpType + item.mnurl
                    return item
                })
                this.ConfigJsInfo = res
                this.xianlu = res.tradeLine[0]
                this.getHeyueinfo(url, parameter);
                return true
            } catch (error) {
                this.fffTime = setTimeout(() => {
                    clearTimeout(this.fffTime)
                    alert('网络错误请检查网络后F5刷新重试！')
                }, 1000)
            }
        },
        setClassHeyueIndex(event) {
            chartStore().bodyType = 'list'
            this.classHeyueIndex = event
            localStorage.setItem('classHeyueIndex', event)
        },
        changeHeyueinfo(event) {
            this.selectHeyue = event
        },
        setRightViewXY(event) {
            this.rightViewXY = event
        },
        setZixuanHeyue(event) {
            if (!this.zixuanHeyue[event.name]) this.zixuanHeyue[event.name] = []
            let index = this.zixuanHeyue[event.name].indexOf(event.id)
            if (event.type == 1) {
                if (index == -1) {
                    this.zixuanHeyue[event.name].push(event.id)
                }
            } else {
                if (index != -1) {
                    this.zixuanHeyue[event.name].splice(index, 1)
                }
            }
            localStorage.setItem('zixuanHeyue', JSON.stringify(this.zixuanHeyue))
        },
    }
})

export const chartStore = defineStore('chart', { //storeChart
    state: () => ({
        bodyType: 'list', //[chart, list]
        selectBodyListTable: localStorage.getItem('selectBodyListTable') || '期货',
        selectbodyChartListTab: '分时图',
        BodyListbottom: ['全部', '主力合约', '自选合约', '隐藏合约', '删除合约'],
        selectBodyListbottom: '全部',
        hangqingMqtt: undefined,
        hagnqingData: undefined,
        hqData: undefined,
        TradetimeList: undefined,
        selecteHangeQingData: undefined,
        lastKLineData: undefined,
        FenshiData: undefined,
        KlineData: [],
        klineCycle: 4,
        KlineAPiVal: '1分钟',
        headApiVal: null,
        yujingList: [],
        yujingCode: {},
        toolMeun: [
            { show: true, name: '', type: '刷新', icon: 'icon-shuaxin' },
            { show: true, name: '', type: '报价', icon: 'icon-baojia-04' },
            { show: true, name: '', type: '分时', icon: 'icon-zhexiantu' },
            { show: true, name: '', type: 'K线', icon: 'icon-kxiantu' },
            { show: true, name: '', type: '账户窗口', icon: 'icon-yongdian' },
            { show: true, name: '', type: '画线下单', icon: 'icon-biaodanziduan' },
            { show: true, name: '', type: '画线单列表', icon: 'icon-weathercloudlightning' },
            { show: true, name: '', type: '预警列表', icon: 'icon-bell' },
            // { show: true, name: '', type: '闪电图', icon: 'icon-fund' },
            { show: true, name: '1', type: '1分钟', icon: '' },
            { show: true, name: '3', type: '3分钟', icon: '' },
            { show: true, name: '5', type: '5分钟', icon: '' },
            { show: true, name: '15', type: '15分钟', icon: '' },
            { show: false, name: '30', type: '30分钟', icon: '' },
            { show: true, name: '1h', type: '一小时', icon: '' },
            { show: true, name: '2h', type: '二小时', icon: '' },
            { show: true, name: '4h', type: '四小时', icon: '' },
            { show: true, name: '日', type: '日线', icon: 'set_size' },
            { show: true, name: '', type: '水平放大', icon: 'icon-shuipingfangda' },
            { show: true, name: '', type: '水平压缩', icon: 'icon-shuipingsuoxiao' },
            { show: true, name: '', type: '左翻K线', icon: 'icon-kongxinzuojiantou' },
            { show: true, name: '', type: '右翻K线', icon: 'icon-kongxinyoujiantou' },
            { show: true, name: '', type: '上翻合约', icon: 'icon-xiangshangzhanhang' },
            { show: true, name: '', type: '下翻合约', icon: 'icon-xiangxiazhanhang' },
            { show: true, name: '', type: '区间选择/统计', icon: 'icon-shuchi' },
            { show: true, isbar: 1, name: '···', type: '其他按钮', icon: '' },
            { show: true, iselect: true, isbar: 2, name: '', type: '画图工具箱', icon: 'icon-huabi' },
        ],
    }),
    actions: {
        changeToolMeun(event) {
            this.toolMeun = event
        },
        changeBodyType(event) {
            this.bodyType = event
        },
        changeSelectBodyListTable(event) {
            this.selectBodyListTable = event
            mainStore().classHeyueIndex = event
            localStorage.setItem('selectBodyListTable', event)
            localStorage.setItem('classHeyueIndex', event)
        },
        changeSelectbodyChartListTab(event) {
            this.selectbodyChartListTab = event
            this.KlineData = []
            bus.emit('changeHeadApiVal', { type: 'clearKLineData' })
        },
        changeSelectBodyListbottom(event) {
            this.selectBodyListbottom = event
        },
        sethangqingMqtt(event) {
            this.hangqingMqtt = event
        },
        changeklineCycle(event) {
            this.klineCycle = event
            this.KlineData = []
        },
        changeKlineAPiVal(event) {
            this.KlineAPiVal = event
        },
        changeHeadApiVal(val) {
            bus.emit('changeHeadApiVal', val)
        },
        setFenshiDataVal(event) {
            this.FenshiData = event
        },
        setFenshiData(event) {
            this.FenshiData = event.split(";").slice(0, -1)
        },
        setlastKLineData(event) {
            let onceData = event.split(",");
            let nowObj = {
                close: onceData[5] * 1,
                high: onceData[3] * 1,
                low: onceData[4] * 1,
                open: onceData[2] * 1,
                time: onceData[1] * 1,
                volume: onceData[6] * 1 < 0 ? 0 : onceData[6] * 1,
            };
            this.lastKLineData = nowObj
        },
        setKlineData(event) {
            let arr = event.split(";").slice(0, -1)
            let KlineData = arr.map(item => {
                let v = item.split(",");
                return {
                    close: v[5] * 1,
                    high: v[3] * 1,
                    low: v[4] * 1,
                    open: v[2] * 1,
                    time: v[1] * 1,
                    volume: v[6] * 1 < 0 ? 0 : v[6] * 1,
                }
            })
            this.KlineData = [...KlineData.reverse()]
        },
        changehagnqingData(event) {
            this.hagnqingData = event
            this.hqData = event
        },
        setHagnqingData(event) {
            let Arr = event.split(";");
            let heyueinfo = mainStore().classHeyue[mainStore().classHeyueIndex]
            // if (mainStore().selectHeyue) {
            //     if (!this.hagnqingData) {
            //         this.hagnqingData = { ...heyueinfo }
            //     }
            //     let obj = this.hagnqingData[mainStore().selectHeyue.heyue_bh]
            //     if (!obj) {
            //         this.hagnqingData[mainStore().selectHeyue.heyue_bh] = mainStore().selectHeyue
            //     }
            // }
            if (Arr[0] == 2 && heyueinfo) {
                let [
                    ,
                    contractCode,
                    updateTime,
                    updateMilli,
                    seller1,
                    sellingVol1,
                    currentPrice,
                    buy1,
                    buyVol1,
                    dailyLimit,
                    downLimit,
                    volume,
                    inventory,
                    openingToday,
                    closingToday,
                    highestPrice,
                    lowestPrice,
                    averageDaily,
                    closedYes,
                    holdingsYes,
                    transaction,
                    settlementYes,
                ] = Arr;
                this.setSelectBodyListHeyueTable(this.hqData)
                this.jaigeYuJing(contractCode, currentPrice, volume, inventory)
                if (!this.hagnqingData) {
                    this.hagnqingData = { ...heyueinfo }
                    if (!this.hqData) {
                        this.hqData = {}
                    }
                    for (let key in heyueinfo) {
                        this.hqData[heyueinfo[key].heyue_id] = heyueinfo[key]
                    }
                }
                if (this.hagnqingData[contractCode]) {
                    // let xianshou = inventory ? this.hagnqingData[contractCode].inventory ? inventory - this.hagnqingData[contractCode].inventory > 0 ? inventory - this.hagnqingData[contractCode].inventory : 1 : 1 : '----'
                    this.hagnqingData[contractCode] = {
                        ...this.hagnqingData[contractCode],
                        nowUpw: upsAndDowns(currentPrice, settlementYes), // 当前涨跌
                        nowGain: figureRange(currentPrice, settlementYes), // 当前涨幅
                        contractCode, // 期货合约代号
                        timestamp: updateTime * 1, // 更新时间戳
                        updateTime: parseTime(updateTime, "{hh}:{ii}:{ss}"), // 更新时间
                        updateMilli, // 更新毫秒
                        seller1: seller1 * 1, // 卖1
                        sellingVol1: sellingVol1 * 1, // 卖1量
                        currentPrice: currentPrice * 1, // 现价
                        buy1: buy1 * 1, // 买1
                        buyVol1: buyVol1 * 1, // 买1量
                        dailyLimit: dailyLimit * 1, // 涨停板价
                        downLimit: downLimit * 1, // 跌停板价
                        volume: volume * 1, // 成交量
                        inventory: inventory * 1, // 矜持长
                        openingToday: openingToday * 1, // 今开盘
                        closingToday: closingToday * 1, // 今收盘
                        highestPrice: highestPrice * 1, // 最高价
                        lowestPrice: lowestPrice * 1, // 最低价
                        averageDaily: averageDaily * 1, // 当日均价
                        closedYes: closedYes * 1, // 昨收盘
                        holdingsYes: holdingsYes * 1, // 昨持仓量
                        transaction: transaction * 1, // 现价
                        settlementYes: settlementYes * 1, // 昨日结算价格
                        rizeng: jsrizeng(inventory, holdingsYes), // 日增
                        xianshou: parseFloat(transaction),
                        flicker: true,
                    }
                    if (!this.hqData) {
                        this.hqData = {}
                    }
                    this.hqData[this.hagnqingData[contractCode].heyue_id] = this.hagnqingData[contractCode]
                }
            }
        },
        setSelectBodyListHeyueTable: throttle(function (hagnqing) {
            if (!hagnqing) return
            let obj = hagnqing[mainStore().selectHeyue.heyue_id]
            if (obj) {
                this.selecteHangeQingData = obj
                return
            }
            this.selecteHangeQingData = mainStore().selectHeyue
        }, 0),
        async jaigeYuJing(contractCode, currentPrice, volume, inventory) {
            await this.jaigeYuJingList()
            if (this.yujingCod[contractCode]) {
                this.yujingCod[contractCode].forEach(item => {
                    let ischufa = []
                    ischufa = item.checkedList.map(sub => {
                        if (sub == 1) {
                            if (currentPrice >= item.priceup) {
                                return true
                            }
                            return false
                        }
                        if (sub == 2) {
                            if (currentPrice >= item.priceup2) {
                                return true
                            }
                            return false
                        }
                        if (sub == 3) {
                            if (currentPrice <= item.priceDown) {
                                return true
                            }
                            return false
                        }
                        if (sub == 4) {
                            if (currentPrice <= item.priceDown2) {
                                return true
                            }
                            return false
                        }
                        if (sub == 5) {
                            if (inventory >= item.inventory) {
                                return true
                            }
                            return false
                        }
                        if (sub == 6) {
                            if (volume >= item.volume) {
                                return true
                            }
                            return false
                        }
                    })
                    if (!ischufa.every(element => element === true)) {
                        return
                    }
                    if (item.chufaStatic == 1 && item.chufaNum != 0) {
                        return
                    }
                    let index = this.yujingList.find(sub => sub.time == item.time)
                    if (index != -1) {
                        item.chufaNum = item.chufaNum * 1 + 1;
                        item.chufanTime = new Date() * 1
                        this.yujingList[index] = item
                        ipcRenderer.send('open-yujingchufalist')
                        tiaoJianTxt.writeYuJing(JSON.stringify(this.yujingList))
                    }
                })
            }
        },
        jaigeYuJingList: throttle(function () {
            this.yujingCod = {}
            this.yujingList = []
            let cont = tiaoJianTxt.readYuJing()
            if (cont) {
                this.yujingList = JSON.parse(cont)
                this.yujingList.forEach(item => {
                    if (this.yujingCod[item.heyue_bh]) {
                        this.yujingCod[item.heyue_bh].push(item)
                    } else {
                        this.yujingCod[item.heyue_bh] = [item]
                    }
                })
            }
        }, 180000),
        async getTradetimeList(url, parameter) {
            let res = await axios.post(mainStore().xianlu.url + '/' + url, parameter)
            this.TradetimeList = res.data
        }
    }
})


function jsrizeng(inventory, holdingsYes) {
    if (inventory && holdingsYes) {
        return inventory - holdingsYes
    }
    return '---'
}
function upsAndDowns(nowp, yesp) {
    let difference = parseFloat(nowp - yesp) * 1
    if (isNaN(difference)) {
        return '---';
    }
    let f = difference.toFixed(5);
    return f;
}

function figureRange(n, y) {
    let difference = parseFloat(n) - parseFloat(y)
    if (isNaN(difference)) {
        return '---';
    }
    let business = difference / y;
    if (isNaN(business)) {
        return '---';
    }
    let r = (business * 100).toFixed(2);
    return r;
}

function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}
